<template>
    <div class="result-board">
        <div class="result-board-text" v-if="gameStore.loser === 'all'">全部阵亡 - 平局</div>
        <div
            class="result-board-text"
            v-else-if="
                (gameStore.loser === 'A' || gameStore.loser.includes('A')) &&
                gameStore.a_id === parseInt(userStore.id)
            "
        >
            失败
        </div>
        <div
            class="result-board-text"
            v-else-if="
                (gameStore.loser === 'B' || gameStore.loser.includes('B')) &&
                gameStore.b_id === parseInt(userStore.id)
            "
        >
            失败
        </div>
        <div
            class="result-board-text"
            v-else-if="
                (gameStore.loser === 'C' || gameStore.loser.includes('C')) &&
                gameStore.c_id === parseInt(userStore.id)
            "
        >
            失败
        </div>
        <div class="result-board-text" v-else>胜利</div>
        <div class="result-board-btn">
            <button @click="restart" type="button" class="btn btn-warning btn-lg">
                再来一次！
            </button>
        </div>
    </div>
</template>

<script>
import { useGameStore } from '@/store/game'
import { useUserStore } from '@/store/user'

export default {
    setup() {
        const gameStore = useGameStore()
        const userStore = useUserStore()

        // 重启游戏时，确保所有状态被正确重置
        const restart = async () => {
            try {
                // 1. 停止所有进行中的动画帧请求
                if (window._animationFrameId) {
                    cancelAnimationFrame(window._animationFrameId)
                    window._animationFrameId = null
                }

                // 2. 获取GameObject类引用，用于清理游戏对象
                let GameObject = null
                if (gameStore.gameObject) {
                    try {
                        GameObject = gameStore.gameObject.constructor.constructor
                        gameStore.gameObject._destroyed = true
                    } catch (e) {
                        console.warn('获取GameObject类引用失败:', e)
                    }
                }

                // 3. 发送游戏结束通知到服务器
                try {
                    if (gameStore.socket && gameStore.socket.readyState === WebSocket.OPEN) {
                        const endGameEvent = { event: 'end-game' }
                        gameStore.socket.send(JSON.stringify(endGameEvent))
                    }
                } catch (e) {
                    console.error('发送游戏结束通知失败:', e)
                }

                // 4. 全局清理所有游戏对象
                try {
                    if (GameObject && typeof GameObject.clearAll === 'function') {
                        GameObject.clearAll()
                    }
                } catch (e) {
                    console.error('清理游戏对象时出错:', e)
                }

                // 5. 清理canvas上下文
                await new Promise((resolve) => {
                    setTimeout(() => {
                        try {
                            // 强制清理canvas引用
                            const canvases = document.querySelectorAll('canvas')
                            for (let canvas of canvases) {
                                // 获取canvas的上下文
                                const ctx = canvas.getContext('2d')
                                if (ctx) {
                                    // 清空画布内容
                                    ctx.clearRect(0, 0, canvas.width, canvas.height)
                                }
                            }
                        } catch (e) {
                            console.warn('清理canvas上下文时出错:', e)
                        }
                        resolve()
                    }, 300)
                })

                // 6. 调用store的resetGame方法重置状态
                gameStore.resetGame()

                // 7. 检查并恢复WebSocket连接
                if (!gameStore.socket || gameStore.socket.readyState !== WebSocket.OPEN) {
                    try {
                        const socketUrl = `wss://www.xujiaojiaojiao.cn/websocket/${userStore.token}`

                        // 关闭可能存在的旧连接
                        if (gameStore.socket) {
                            try {
                                if (gameStore.socket.readyState !== WebSocket.CLOSED) {
                                    gameStore.socket.close()
                                }
                            } catch (e) {
                                console.warn('关闭旧WebSocket连接时出错:', e)
                            }
                        }

                        // 创建新连接
                        const newSocket = new WebSocket(socketUrl)

                        // 设置基本事件处理
                        newSocket.onopen = () => {}
                        newSocket.onerror = (error) => {
                            console.error('WebSocket连接出错:', error)
                        }

                        // 等待连接建立
                        await new Promise((resolve) => {
                            // 最多等待3秒
                            const timeout = setTimeout(() => {
                                resolve()
                            }, 3000)

                            // 连接成功
                            newSocket.onopen = () => {
                                clearTimeout(timeout)
                                resolve()
                            }

                            // 连接失败
                            newSocket.onerror = () => {
                                clearTimeout(timeout)
                                resolve()
                            }
                        })

                        // 更新store中的socket引用
                        gameStore.updateSocket(newSocket)

                        // 发送ping消息测试连接
                        if (newSocket.readyState === WebSocket.OPEN) {
                            newSocket.send(JSON.stringify({ event: 'ping' }))
                        }
                    } catch (e) {
                        console.error('建立WebSocket连接时出错:', e)
                    }
                } else {
                    try {
                        gameStore.socket.send(JSON.stringify({ event: 'ping' }))
                    } catch (e) {
                        // 如果发送失败，重新创建连接
                        const socketUrl = `wss://www.xujiaojiaojiao.cn/websocket/${userStore.token}`
                        gameStore.socket = new WebSocket(socketUrl)
                    }
                }
            } catch (error) {
                console.error('游戏重启过程中出错:', error)

                // 即使出错，也尝试最基本的状态重置
                try {
                    gameStore.resetGame()
                } catch (e) {
                    console.error('重置游戏状态时出错:', e)
                }
            }
        }

        return {
            restart,
            gameStore,
            userStore,
        }
    },
}
</script>

<style scoped>
div.result-board {
    position: absolute;
    top: 30vh;
    left: 35vw;
    width: 30vw;
    height: 30vh;
    background-color: rgba(0, 0, 0, 0.5);
}
div.result-board-text {
    text-align: center;
    color: white;
    font-size: 50px;
    font-weight: 600;
    font-style: italic;
    padding-top: 5vh;
}

div.result-board-btn {
    padding-top: 7vh;
    text-align: center;
}
</style>
